#!/bin/sh

source "${BASH_SOURCE%/*}/logger.sh"
source "${BASH_SOURCE%/*}/migrate-registry-storage"

# This script takes a v1.x.x install and updates the compose stack to use S3 as your
# registry storage.

source "${BASH_SOURCE%/*}/_realpath"

DIR="$(dirname $(realpath "$0"))"
BASE_DIR="$(dirname "${DIR}")"
CONFIG_DIR="${BASE_DIR}/config"
CONFIG_FILE="${CONFIG_DIR}/activate"

# Step 1. Make sure a config exists...
[ -f "${CONFIG_FILE}" ] || die "Unable to find existing config!";

info "Preparing to upgrade..."
source "${CONFIG_FILE}"

while getopts "f" opt; do
  case "${opt}" in
    f) 
        warn "Forcing upgrade! I hope you know what you're doing..."
        FORCE_UPGRADE=1
        ;;
    *)
      echo "Invalid argument: ${OPTARG}"
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

# Step 2. Check if the S3 configuration already exists...
upgrade_required () {
    [ -z "${OPENBALENA_REGISTRY2_S3_BUCKET}" ] || return 1;
    [ -z "${OPENBALENA_S3_ACCESS_KEY}" ] || return 1;
    [ -z "${OPENBALENA_S3_ENDPOINT}" ] || return 1;
    [ -z "${OPENBALENA_S3_REGION}" ] || return 1;
    [ -z "${OPENBALENA_S3_SECRET_KEY}" ] || return 1;
}
upgrade_required || die_unless_forced "${FORCE_UPGRADE}" "Configuration may already be using S3 for Registry storage!"

# Step 3. Create missing S3 configuration...
randstr() {
  LC_CTYPE=C tr -dc A-Za-z0-9 < /dev/urandom | fold -w "${1:-32}" | head -n 1
}

upsert_config () {
    var="${1}"
    value="${2}"

    if [ -z "${!var}" ]; then
        echo "export ${1}=${2}" >> "${CONFIG_FILE}"
    else
        sed -i '' "s~export ${1}=.*~export ${1}=${2}~" "${CONFIG_FILE}"
    fi
}

upsert_config "OPENBALENA_REGISTRY2_S3_BUCKET" "registry-data" || warn "Failed to update config value OPENBALENA_REGISTRY2_S3_BUCKET"
upsert_config "OPENBALENA_S3_ACCESS_KEY" "$(randstr 32)" || warn "Failed to update config value OPENBALENA_S3_ACCESS_KEY"
upsert_config "OPENBALENA_S3_ENDPOINT" "https://s3.${OPENBALENA_HOST_NAME}" || warn "Failed to update config value OPENBALENA_S3_ENDPOINT"
upsert_config "OPENBALENA_S3_REGION" "us-east-1" || warn "Failed to update config value OPENBALENA_S3_REGION"
upsert_config "OPENBALENA_S3_SECRET_KEY" "$(randstr 32)" || warn "Failed to update config value OPENBALENA_S3_SECRET_KEY"

# Step 4. Migrate Registry data to S3...
info "Copying data from the Registry volume to the S3 volume..."
migrate_data_to_s3 "registry-data"
case $? in
    1)  die "Invalid bucket name";;
    2)  die "Unable to find the running Registry or S3 containers";;
    3)  die "Unable to determine the data volumes for the Registry or S3 containers";;
    *)  info "Registry data copied"
        ;;
esac
info "Upgrade complete"